/**
 * @file auth_service_test.cpp
 * @brief 认证授权服务测试
 * @author 29108
 * @date 2025/7/19
 * @version 1.0
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "core_services/auth_service/auth_service.h"
#include "core_services/auth_service/jwt_manager.h"
#include "core_services/auth_service/user_repository.h"
#include "core_services/auth_service/session_manager.h"

using namespace core_services::auth_service;

class AuthServiceTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 设置测试配置
        config_.server_config.host = "127.0.0.1";
        config_.server_config.port = 8082;
        config_.server_config.worker_threads = 2;
        
        config_.jwt_config.secret_key = "test_secret_key";
        config_.jwt_config.access_token_expire_seconds = 3600;
        config_.jwt_config.refresh_token_expire_seconds = 604800;
        
        config_.database_config.mysql_host = "localhost";
        config_.database_config.mysql_port = 3306;
        config_.database_config.mysql_user = "test_user";
        config_.database_config.mysql_password = "test_password";
        config_.database_config.mysql_database = "test_auth_db";
        
        config_.database_config.redis_host = "localhost";
        config_.database_config.redis_port = 6379;
        config_.database_config.redis_database = 1; // 使用测试数据库
        
        config_.enable_password_complexity = true;
        config_.min_password_length = 8;
    }
    
    void TearDown() override {
        // 清理测试数据
    }
    
    AuthService::Config config_;
};

// ==================== UserInfo 测试 ====================

TEST(UserInfoTest, BasicFunctionality) {
    UserInfo user("testuser", "test@example.com", "hashed_password", "salt123");
    
    EXPECT_EQ(user.username, "testuser");
    EXPECT_EQ(user.email, "test@example.com");
    EXPECT_TRUE(user.validate());
    EXPECT_FALSE(user.isAdmin());
    EXPECT_FALSE(user.isActive()); // 默认状态是INACTIVE
    
    user.status = UserStatus::ACTIVE;
    EXPECT_TRUE(user.isActive());
    
    user.role = UserRole::ADMIN;
    EXPECT_TRUE(user.isAdmin());
}

TEST(UserInfoTest, JsonSerialization) {
    UserInfo user("testuser", "test@example.com", "hashed_password", "salt123");
    user.user_id = 123;
    user.nickname = "Test User";
    user.role = UserRole::PLAYER;
    user.status = UserStatus::ACTIVE;
    user.game_level = 10;
    user.game_coins = 1000;
    user.permissions = {"user.read", "game.play"};
    
    // 测试JSON序列化
    auto json = user.toJson();
    EXPECT_EQ(json["user_id"], 123);
    EXPECT_EQ(json["username"], "testuser");
    EXPECT_EQ(json["email"], "test@example.com");
    EXPECT_EQ(json["nickname"], "Test User");
    EXPECT_EQ(json["role"], static_cast<int>(UserRole::PLAYER));
    EXPECT_EQ(json["status"], static_cast<int>(UserStatus::ACTIVE));
    EXPECT_EQ(json["game_level"], 10);
    EXPECT_EQ(json["game_coins"], 1000);
    
    // 测试安全JSON序列化（不包含敏感信息）
    auto safe_json = user.toSafeJson();
    EXPECT_FALSE(safe_json.contains("password_hash"));
    EXPECT_FALSE(safe_json.contains("salt"));
    EXPECT_EQ(safe_json["username"], "testuser");
    EXPECT_EQ(safe_json["role"], "PLAYER");
    EXPECT_EQ(safe_json["status"], "ACTIVE");
    
    // 测试JSON反序列化
    auto deserialized_user = UserInfo::fromJson(json);
    EXPECT_EQ(deserialized_user.user_id, user.user_id);
    EXPECT_EQ(deserialized_user.username, user.username);
    EXPECT_EQ(deserialized_user.email, user.email);
    EXPECT_EQ(deserialized_user.role, user.role);
    EXPECT_EQ(deserialized_user.status, user.status);
}

TEST(UserInfoTest, PermissionCheck) {
    UserInfo user;
    user.permissions = {"user.read", "user.write", "game.play"};
    
    EXPECT_TRUE(user.hasPermission("user.read"));
    EXPECT_TRUE(user.hasPermission("user.write"));
    EXPECT_TRUE(user.hasPermission("game.play"));
    EXPECT_FALSE(user.hasPermission("admin.access"));
    EXPECT_FALSE(user.hasPermission(""));
}

// ==================== JwtManager 测试 ====================

TEST(JwtManagerTest, TokenGeneration) {
    JwtManager::Config config;
    config.secret_key = "test_secret_key";
    config.access_token_expire_seconds = 3600;
    config.refresh_token_expire_seconds = 604800;
    
    JwtManager jwt_manager(config);
    
    UserInfo user("testuser", "test@example.com", "hashed_password", "salt123");
    user.user_id = 123;
    user.role = UserRole::PLAYER;
    user.status = UserStatus::ACTIVE;
    
    // 测试访问令牌生成
    std::string access_token = jwt_manager.generateAccessToken(user);
    EXPECT_FALSE(access_token.empty());
    
    // 测试刷新令牌生成
    std::string refresh_token = jwt_manager.generateRefreshToken(user);
    EXPECT_FALSE(refresh_token.empty());
    
    // 测试令牌对生成
    auto token_pair = jwt_manager.generateTokenPair(user);
    EXPECT_FALSE(token_pair.first.empty());
    EXPECT_FALSE(token_pair.second.empty());
}

TEST(JwtManagerTest, TokenValidation) {
    JwtManager::Config config;
    config.secret_key = "test_secret_key";
    config.access_token_expire_seconds = 3600;
    config.refresh_token_expire_seconds = 604800;
    
    JwtManager jwt_manager(config);
    
    UserInfo user("testuser", "test@example.com", "hashed_password", "salt123");
    user.user_id = 123;
    user.role = UserRole::PLAYER;
    user.status = UserStatus::ACTIVE;
    
    // 生成令牌
    std::string access_token = jwt_manager.generateAccessToken(user);
    std::string refresh_token = jwt_manager.generateRefreshToken(user);
    
    // 验证访问令牌
    auto access_validation = jwt_manager.validateAccessToken(access_token);
    EXPECT_TRUE(access_validation.valid);
    EXPECT_EQ(access_validation.user_info.user_id, user.user_id);
    EXPECT_EQ(access_validation.user_info.username, user.username);
    
    // 验证刷新令牌
    auto refresh_validation = jwt_manager.validateRefreshToken(refresh_token);
    EXPECT_TRUE(refresh_validation.valid);
    EXPECT_EQ(refresh_validation.user_info.user_id, user.user_id);
    
    // 测试无效令牌
    auto invalid_validation = jwt_manager.validateAccessToken("invalid_token");
    EXPECT_FALSE(invalid_validation.valid);
    EXPECT_FALSE(invalid_validation.error_message.empty());
}

TEST(JwtManagerTest, TokenBlacklist) {
    JwtManager::Config config;
    config.secret_key = "test_secret_key";
    config.enable_token_blacklist = true;
    
    JwtManager jwt_manager(config);
    
    UserInfo user("testuser", "test@example.com", "hashed_password", "salt123");
    user.user_id = 123;
    
    std::string token = jwt_manager.generateAccessToken(user);
    
    // 令牌应该有效
    auto validation = jwt_manager.validateAccessToken(token);
    EXPECT_TRUE(validation.valid);
    
    // 撤销令牌
    EXPECT_TRUE(jwt_manager.revokeToken(token));
    EXPECT_TRUE(jwt_manager.isTokenBlacklisted(token));
    
    // 撤销后令牌应该无效
    validation = jwt_manager.validateAccessToken(token);
    EXPECT_FALSE(validation.valid);
    EXPECT_EQ(validation.error_message, "Token is blacklisted");
}

// ==================== 辅助函数测试 ====================

TEST(UtilityFunctionsTest, RoleConversion) {
    EXPECT_EQ(userRoleToString(UserRole::GUEST), "GUEST");
    EXPECT_EQ(userRoleToString(UserRole::PLAYER), "PLAYER");
    EXPECT_EQ(userRoleToString(UserRole::VIP), "VIP");
    EXPECT_EQ(userRoleToString(UserRole::MODERATOR), "MODERATOR");
    EXPECT_EQ(userRoleToString(UserRole::ADMIN), "ADMIN");
    EXPECT_EQ(userRoleToString(UserRole::SUPER_ADMIN), "SUPER_ADMIN");
    
    EXPECT_EQ(stringToUserRole("GUEST"), UserRole::GUEST);
    EXPECT_EQ(stringToUserRole("PLAYER"), UserRole::PLAYER);
    EXPECT_EQ(stringToUserRole("VIP"), UserRole::VIP);
    EXPECT_EQ(stringToUserRole("MODERATOR"), UserRole::MODERATOR);
    EXPECT_EQ(stringToUserRole("ADMIN"), UserRole::ADMIN);
    EXPECT_EQ(stringToUserRole("SUPER_ADMIN"), UserRole::SUPER_ADMIN);
    EXPECT_EQ(stringToUserRole("INVALID"), UserRole::PLAYER); // 默认值
}

TEST(UtilityFunctionsTest, StatusConversion) {
    EXPECT_EQ(userStatusToString(UserStatus::INACTIVE), "INACTIVE");
    EXPECT_EQ(userStatusToString(UserStatus::ACTIVE), "ACTIVE");
    EXPECT_EQ(userStatusToString(UserStatus::SUSPENDED), "SUSPENDED");
    EXPECT_EQ(userStatusToString(UserStatus::BANNED), "BANNED");
    
    EXPECT_EQ(stringToUserStatus("INACTIVE"), UserStatus::INACTIVE);
    EXPECT_EQ(stringToUserStatus("ACTIVE"), UserStatus::ACTIVE);
    EXPECT_EQ(stringToUserStatus("SUSPENDED"), UserStatus::SUSPENDED);
    EXPECT_EQ(stringToUserStatus("BANNED"), UserStatus::BANNED);
    EXPECT_EQ(stringToUserStatus("INVALID"), UserStatus::INACTIVE); // 默认值
}

// ==================== 集成测试 ====================

TEST_F(AuthServiceTest, ConfigValidation) {
    EXPECT_TRUE(config_.validate());
    
    // 测试无效配置
    AuthService::Config invalid_config = config_;
    invalid_config.min_password_length = 0;
    EXPECT_FALSE(invalid_config.validate());
}

// 主函数
int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
